import React, { useRef } from 'react';
import { Editor } from '@tinymce/tinymce-react';
// import './zh-Hans'


function Rich() {
  const editorRef = useRef(null);
  const log = () => {
    if (editorRef.current) {
      console.log(editorRef.current.getContent());
    }
  };
  const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.withCredentials = false;
    xhr.open('POST', 'http://dida100.com:8889/api/upload');
  
    xhr.upload.onprogress = (e) => {
      progress(e.loaded / e.total * 100);
    };
  
    xhr.onload = () => {
      if (xhr.status === 403) {
        reject({ message: 'HTTP Error: ' + xhr.status, remove: true });
        return;
      }
  
      if (xhr.status < 200 || xhr.status >= 300) {
        reject('HTTP Error: ' + xhr.status);
        return;
      }
  
      const json = JSON.parse(xhr.responseText);
  
      // if (!json || typeof json.location != 'string') {
      //   reject('Invalid JSON: ' + xhr.responseText);
      //   return;
      // }
      console.log(json,"json");
      resolve('http://dida100.com:8889'+json.file.path )
      // resolve(json.location);
    };
  
    xhr.onerror = () => {
      reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
    };
  
    const formData = new FormData();
    formData.append('file', blobInfo.blob(), blobInfo.filename());
  
    xhr.send(formData);
  });

  return ( <div style={{padding:100}}>
    <h3>富文本编辑器</h3>
    <Editor
        apiKey='adolg3do84vg41ddoak4nwkas81yke42vopk0o9rsmfy9hyp'
        onInit={(evt, editor) => editorRef.current = editor}
        initialValue="<p>请输入内容</p>"
        init={{
          height: 500,
          language:'zh_CN',
          menubar: false,
          images_upload_handler: example_image_upload_handler,
          plugins: [
            'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
            'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount'
          ],
          toolbar: 'undo redo | blocks | ' +
            'bold italic forecolor | image table code |alignleft aligncenter ' +
            'alignright alignjustify | bullist numlist outdent indent | ' +
            'removeformat | help',
          content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
        }}
      />
      <button onClick={log}>Log editor content</button>
  </div> );
}

export default Rich;